﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BilingualSentSearchEngine
{
    class UserInfo
    {
        public DateTime dtLastAccess;
        public int iAccessCnt;

        public UserInfo()
        {
            dtLastAccess = DateTime.Now;
            iAccessCnt = 0;
        }
    }

    class UserAgent
    {
        int iMaxAccessCnt;
        int iAccessSpanHours;
        Dictionary<string, UserInfo> user2info;
        object _privateObject = new object();

        public UserAgent(int maxAccessCnt, int accessSpanHour)
        {
            iMaxAccessCnt = maxAccessCnt;
            iAccessSpanHours = accessSpanHour;
            user2info = new Dictionary<string, UserInfo>();
        }

        public int GetAccessSpanHours()
        {
            return iAccessSpanHours;
        }

        public bool IsInvalidate(ref string strUserId)
        {
            lock (_privateObject)
            {
                if (user2info.Count > 65535)
                {
                    user2info = new Dictionary<string, UserInfo>();
                }

                if (user2info.ContainsKey(strUserId) == false)
                {
                    user2info.Add(strUserId, new UserInfo());

                    return true;
                }
                else
                {
                    if (user2info[strUserId].iAccessCnt < iMaxAccessCnt)
                    {
                        if (DateTime.Now.Subtract(user2info[strUserId].dtLastAccess).Hours >= iAccessSpanHours)
                        {
                            user2info[strUserId].iAccessCnt = 0;
                        }
                        else
                        {
                            user2info[strUserId].iAccessCnt++;
                        }
                        user2info[strUserId].dtLastAccess = DateTime.Now;

                        return true;
                    }
                    else
                    {
                        if (DateTime.Now.Subtract(user2info[strUserId].dtLastAccess).Hours > iAccessSpanHours)
                        {
                            user2info[strUserId].iAccessCnt = 0;
                            user2info[strUserId].dtLastAccess = DateTime.Now;

                            return true;
                        }
                        else
                        {
                            return false;
                        }

                    }
                }
            }
        }
    }
}
